<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>AOP in JavaScript | 在路上</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="基本概念面向侧面的程序设计（aspect-oriented programming，AOP，又译作面向方面的程序设计、观点导向编程）是计算机科学中的一个术语，指一种程序设计范型。 该范型以一种称为侧面（aspect，又译作方面）的语言构造为基础，侧面是一种新的模块化机制，用来描述分散在对象、类或函数中的 横切关注点 （crosscutting concern）。 使用目的需要增强或者修改原有函数的">
<meta name="keywords" content="JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="AOP in JavaScript">
<meta property="og:url" content="http://yoursite.com/2012/03/18/AOP-in-JavaScript/index.html">
<meta property="og:site_name" content="在路上">
<meta property="og:description" content="基本概念面向侧面的程序设计（aspect-oriented programming，AOP，又译作面向方面的程序设计、观点导向编程）是计算机科学中的一个术语，指一种程序设计范型。 该范型以一种称为侧面（aspect，又译作方面）的语言构造为基础，侧面是一种新的模块化机制，用来描述分散在对象、类或函数中的 横切关注点 （crosscutting concern）。 使用目的需要增强或者修改原有函数的">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-03-26T11:35:06.673Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="AOP in JavaScript">
<meta name="twitter:description" content="基本概念面向侧面的程序设计（aspect-oriented programming，AOP，又译作面向方面的程序设计、观点导向编程）是计算机科学中的一个术语，指一种程序设计范型。 该范型以一种称为侧面（aspect，又译作方面）的语言构造为基础，侧面是一种新的模块化机制，用来描述分散在对象、类或函数中的 横切关注点 （crosscutting concern）。 使用目的需要增强或者修改原有函数的">
  
    <link rel="alternate" href="/atom.xml" title="在路上" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">在路上</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">一位崇尚价值投资的 Web 开发者</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-AOP-in-JavaScript" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2012/03/18/AOP-in-JavaScript/" class="article-date">
  <time datetime="2012-03-17T16:00:00.000Z" itemprop="datePublished">2012-03-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      AOP in JavaScript
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="基本概念"><a href="#基本概念" class="headerlink" title="基本概念"></a>基本概念</h2><p><code>面向侧面的程序设计</code>（aspect-oriented programming，AOP，又译作面向方面的程序设计、观点导向编程）是计算机科学中的一个术语，指一种程序设计范型。</p>
<p>该范型以一种称为侧面（aspect，又译作方面）的语言构造为基础，侧面是一种新的模块化机制，用来描述分散在对象、类或函数中的 <code>横切关注点</code> （crosscutting concern）。</p>
<h2 id="使用目的"><a href="#使用目的" class="headerlink" title="使用目的"></a>使用目的</h2><p>需要增强或者修改原有函数的功能，但并不直接修改原函数的内部逻辑。比如为函数添加 <code>前置</code> 和 <code>后置</code> 操作。</p>
<p>最常见的应用比如计算函数执行的时间、函数执行时的<code>日志记录</code>。</p>
<h2 id="实际应用"><a href="#实际应用" class="headerlink" title="实际应用"></a>实际应用</h2><p>在系统中有两个函数，func1和func2，func2是func1代码末尾的JSONP（跨域请求）回调。这两个函数内部逻辑相对复杂，代码也较多。</p>
<p>func1的执行频率是10秒一次，而客户端与服务器之间的网络并不能保证永远正常连接，除了后端有DNSPOD、反向代理等容灾方案，前端也要做一些容灾工作。</p>
<p><code>如何容灾</code> ？就是在发现连续两次请求失败，就认定主服务器不可用，立刻在前端切换到备用服务器。<br>确定好这个思路以后剩下的就是在服务端添加各种配置，然后在前端为原有的func1加入请求超时的统计功能。</p>
<p>超时统计无非就是在func1的开始设置一个变量，func2结束后还原为初始值，如果在指定的超时时间段内发现变量未还原则判定为请求超时。</p>
<p>这段代码与原函数func1和func2均无逻辑关联，所以尽量不直接修改这2个函数的代码，<br>加之func1和func2已经相对复杂，若直接修改函数内部代码将导致代码复杂度加倍而且难于维护。</p>
<p>于是乎，AOP就派上用场了！</p>
<h2 id="实现代码"><a href="#实现代码" class="headerlink" title="实现代码"></a>实现代码</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> _ = <span class="function"><span class="keyword">function</span>(<span class="params">id</span>)</span>&#123;<span class="keyword">return</span> <span class="built_in">document</span>.getElementById(id);&#125;;</span><br><span class="line"><span class="keyword">var</span> GFRAME = &#123;&#125;;</span><br><span class="line">GFRAME.name = <span class="string">'GFRAME'</span>;</span><br><span class="line">GFRAME.func1 = <span class="function"><span class="keyword">function</span>(<span class="params">x</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.name,x);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * @description AOP in JavaScript，不直接修改原函数而增强函数功能。未考虑前置操作的函数返回值的情况</span></span><br><span class="line"><span class="comment"> * @param &#123;Object&#125; args &#123;context:执行环境，name:函数名称，start:前置操作，end:后置操作&#125;</span></span><br><span class="line"><span class="comment"> **/</span></span><br><span class="line">_.inject = <span class="function"><span class="keyword">function</span>(<span class="params">args</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> origin = args.name,</span><br><span class="line">        context = args.context || <span class="built_in">window</span>,</span><br><span class="line">        start = args.start || (<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;),</span><br><span class="line">        end = args.end || (<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;);</span><br><span class="line">    <span class="keyword">var</span> temp = context[origin];</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">typeof</span> temp != <span class="string">'function'</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="built_in">Error</span>(origin + <span class="string">' is not a function in the given context.'</span>);</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">typeof</span> start != <span class="string">'function'</span> || <span class="keyword">typeof</span> end != <span class="string">'function'</span> )</span><br><span class="line">        <span class="keyword">throw</span> <span class="built_in">Error</span>(<span class="string">'start and end is not a function in the given context.'</span>);</span><br><span class="line">    context[origin] = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        start.apply(<span class="keyword">this</span>,<span class="built_in">arguments</span>);</span><br><span class="line">        <span class="keyword">var</span> ret = temp.apply(<span class="keyword">this</span>,<span class="built_in">arguments</span>);</span><br><span class="line">        end.apply(<span class="keyword">this</span>,<span class="built_in">arguments</span>);</span><br><span class="line">        <span class="keyword">return</span> ret;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="使用方法"><a href="#使用方法" class="headerlink" title="使用方法"></a>使用方法</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">_.inject(&#123;</span><br><span class="line">    name:<span class="string">'func1'</span>,</span><br><span class="line">    context:GFRAME,</span><br><span class="line">    start:<span class="function"><span class="keyword">function</span>(<span class="params">x</span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'start'</span>,<span class="keyword">this</span>.name,x);</span><br><span class="line">    &#125;,</span><br><span class="line">    end:<span class="function"><span class="keyword">function</span>(<span class="params">x</span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'end'</span>,<span class="keyword">this</span>.name,x);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line">GFRAME.func1(<span class="string">'test'</span>);</span><br></pre></td></tr></table></figure>
<h2 id="输出结果"><a href="#输出结果" class="headerlink" title="输出结果"></a>输出结果</h2><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">start GFRAME test</span><br><span class="line">GFRAME test</span><br><span class="line">end GFRAME test</span><br></pre></td></tr></table></figure>
<h2 id="扩展阅读"><a href="#扩展阅读" class="headerlink" title="扩展阅读"></a>扩展阅读</h2><ul>
<li><a href="http://zh.wikipedia.org/wiki/AOP" target="_blank" rel="noopener">AOP@维基百科</a></li>
<li><a href="http://www.cnblogs.com/riceball/archive/2007/09/02/jsInject.html" target="_blank" rel="noopener">你相信么，只需一个函数5行JS代码即可在Javascript中实现完整的AOP功能</a></li>
</ul>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2012/03/18/AOP-in-JavaScript/" data-id="cjf865ueq00008wp1dhgnzuzf" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript/">JavaScript</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2012/03/28/关于容灾，前端能够做什么/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          关于容灾，前端能够做什么
        
      </div>
    </a>
  
  
    <a href="/2012/02/06/JavaScript-Template-Engine/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">JavaScript Template Engine</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript/">JavaScript</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript-解析器/">JavaScript,解析器</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/React/">React</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Redux/">Redux</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/SlimerJS/">SlimerJS</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/代码管理/">代码管理</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/持续集成/">持续集成</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签云</h3>
    <div class="widget tagcloud">
      <a href="/tags/JavaScript/" style="font-size: 20px;">JavaScript</a> <a href="/tags/JavaScript-解析器/" style="font-size: 10px;">JavaScript,解析器</a> <a href="/tags/React/" style="font-size: 16.67px;">React</a> <a href="/tags/Redux/" style="font-size: 10px;">Redux</a> <a href="/tags/SlimerJS/" style="font-size: 10px;">SlimerJS</a> <a href="/tags/代码管理/" style="font-size: 10px;">代码管理</a> <a href="/tags/持续集成/" style="font-size: 13.33px;">持续集成</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/09/">九月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/07/">七月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/06/">六月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/03/">三月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/02/">二月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/12/">十二月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/06/">六月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/05/">五月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/04/">四月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/07/">七月 2014</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/06/">六月 2014</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/11/">十一月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/10/">十月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/07/">七月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/03/">三月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/02/">二月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2011/10/">十月 2011</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2010/01/">一月 2010</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/1970/01/">一月 1970</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2016/09/09/space/">空格</a>
          </li>
        
          <li>
            <a href="/2016/07/17/parser/">JavaScript Parser资源总结</a>
          </li>
        
          <li>
            <a href="/2016/06/29/slimerjs/">使用SlimerJS将网页输出为PDF</a>
          </li>
        
          <li>
            <a href="/2016/06/26/code-management/">代码管理</a>
          </li>
        
          <li>
            <a href="/2016/06/18/violet/">violet - 值得一试的写作同步小助手</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2018 Simon Xu<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>



  </div>
</body>
</html>